#include <sys_config.h>
#include <sys_parameters.h>
#include <api/libc/printf.h>
#include <api/libc/string.h>
#include <api/libchunk/chunk.h>
#include <bus/sci/sci.h>
#include <bus/flash/flash.h>
#include <hal/hal_gpio.h>
#include <hal/hal_mem.h>
#include <hld/pan/pan_dev.h>
#include <hld/pan/pan.h>
#include <api/libloader/ld_boot_info.h>

#include "boot_system_data.h"

extern struct sto_device *flash_dev;

union BOOT_INFO boot_system_data;
UINT32 boot_info_addr;//

void boot_sys_data_init()
{
	UINT8 i;
	
	boot_system_data.s_info.boot_display_mode = 0;
	boot_system_data.s_info.boot_tv_ratio = 0;
	boot_system_data.s_info.boot_display_mode = 0;
	boot_system_data.s_info.boot_scart_out = 0;
	for(i=0;i<VDAC_NUM_MAX;i++)
		boot_system_data.s_info.vdac_out[i] = 0;

	boot_system_data.s_info.ota_flag = 0;

	MEMSET(&boot_system_data.s_info.antenna_info, 0, sizeof(struct ft_antenna));
	boot_system_data.s_info.antenna_info.antenna_enable = 1;
	boot_system_data.s_info.antenna_info.lnb_high = 5150;
	boot_system_data.s_info.antenna_info.lnb_low = 5150;

	boot_system_data.s_info.ota_frequency = OTA_FREQUENCY;
	boot_system_data.s_info.ota_symbol = OTA_SYM_RATE;
	
	boot_system_data.s_info.ota_pid = 1277;

	boot_system_data.s_info.sw_version = 1;
	
}

INT32 boot_sys_data_load(union BOOT_INFO *boot_info)
{
	int i;
	INT32 ret;
	UINT32 userdb_chid, userdb_addr, userdb_len;
	UINT32 tmpinfo_addr,tmpinfo_len;
	UINT8 tmp_data[4];

	MEMSET(boot_info, 0, sizeof(union BOOT_INFO));

	userdb_chid = 0x04FB0100;
	userdb_addr = sto_chunk_goto(&userdb_chid, 0xFFFFFFFF, 1);
	if(userdb_addr == (UINT32)ERR_FAILUE)
		return !SUCCESS;
	userdb_len = sto_fetch_long((UINT32)userdb_addr + CHUNK_LENGTH)- 0x70;
	/* seek the last node for tmp info */
	tmpinfo_addr = userdb_addr+0x200 - (userdb_addr+0x200)%(64*1024) + userdb_len - 4;
	tmpinfo_len = 0x10000-4;

	while((sto_fetch_long(tmpinfo_addr)) == 0xFFFFFFFF&&tmpinfo_len > 0)
	{
		tmpinfo_len -= 4;
		tmpinfo_addr -= 4;
	}
	while(tmpinfo_len > 0)
	{
		sto_get_data(flash_dev,tmp_data,tmpinfo_addr,1);
		sto_get_data(flash_dev,tmp_data+1,tmpinfo_addr-1,1);
		sto_get_data(flash_dev,tmp_data+2,tmpinfo_addr-2,1);
		sto_get_data(flash_dev,tmp_data+3,tmpinfo_addr-3,1);
		if(tmp_data[0] == 0x12&&tmp_data[1] == 0x34
			&&tmp_data[2] == 0x56&&tmp_data[3] == 0x78)
			break;
		tmpinfo_len -= 1;
		tmpinfo_addr -= 1;
	}

	if(tmpinfo_len > 0)
	{
		boot_info_addr=tmpinfo_addr+1;
		if(sto_get_data(flash_dev, (UINT8*)boot_info, tmpinfo_addr+1, sizeof(union BOOT_INFO))==sizeof(union BOOT_INFO))
			return SUCCESS;
	}

	return !SUCCESS;
}

INT32 boot_sys_data_save(union BOOT_INFO *boot_info)
{
	return sto_put_data(flash_dev, boot_info_addr, (UINT8*)boot_info, sizeof(union BOOT_INFO));
}

union BOOT_INFO* get_boot_info()
{
	return &boot_system_data;
}

